package com.zong.ai.agent.demo;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;

/**
 * @author: zongzi
 * @description: 阿里灵积大模型 http 测试类
 * @date: 2025/6/10
 */
public class DashScopeHttpAiTest {

    private static final String API_URL = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation";

    public static void main(String[] args) {
        try {
            String response = callDashScopeApi();
            System.out.println("响应结果：" + response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String callDashScopeApi() {
        // 构建请求体
        JSONObject requestBody = buildRequestBody();

        // 发送HTTP请求
        HttpResponse response = HttpRequest.post(API_URL)
                .header("Authorization", "Bearer " + Constant.API_KEY)
                .header("Content-Type", "application/json")
                .body(requestBody.toString())
                .execute();

        return response.body();
    }

    private static JSONObject buildRequestBody() {
        // 构建messages数组
        JSONArray messages = new JSONArray();

        // 添加system消息
        JSONObject systemMessage = new JSONObject();
        systemMessage.put("role", "system");
        systemMessage.put("content", "You are a helpful assistant.");
        messages.add(systemMessage);

        // 添加user消息
        JSONObject userMessage = new JSONObject();
        userMessage.put("role", "user");
        userMessage.put("content", "你是谁？");
        messages.add(userMessage);

        // 构建input对象
        JSONObject input = new JSONObject();
        input.put("messages", messages);

        // 构建parameters对象
        JSONObject parameters = new JSONObject();
        parameters.put("result_format", "message");

        // 构建完整的请求体
        JSONObject requestBody = new JSONObject();
        requestBody.put("model", "qwen-plus");
        requestBody.put("input", input);
        requestBody.put("parameters", parameters);

        return requestBody;
    }
}